/**
 * <p>Copyright (c) 2017 深圳市鹏途交通科技有限公司</p>
 * <p>					All right reserved. 		 </p>
 * <p>项目名称 ： 	深圳市道路养护管理系统        </p>
 * <p>创建者   :	 刘波波 
 * <p>描   述  :     </p>
 */
package com.pengtu.service.test2;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;

/**
 * @author 刘波波
 * @date  2017/4/7
 * @describe handler处理类
 */
public class AssignTimeHandler extends ChannelOutboundHandlerAdapter {

	

	/**
	 *@author 刘波波
	 *@date 2017年4月11日
	 *@describe 
	 */
	public AssignTimeHandler() {
		super();
	}

	public static String toStringHex1(String s) {  
		byte[] baKeyword = new byte[s.length() / 2];
		for (int i = 0; i < baKeyword.length; i++) {
			try {
				baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		try {
			s = new String(baKeyword, "ASCII");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return s;
	}
	
	

	/**
	 *@author 刘波波
	 *@date 2017年4月27日
	 *@describe 
	 */
	@Override
	public void write(ChannelHandlerContext ctx, Object msg,
			ChannelPromise promise) throws Exception {
		//反馈数据报长度为定长13个字节
		String head = "AAAA";
		String end = "EEEE";
		String u = "4142433132330000";
		String p = "4142433132330000";
		String deviceNo = "30333131313733313037353531363037";
		String returnresult = "290009" + deviceNo + u + p + "E107041101000F00";
		String crcString = returnresult.substring(4);
		//crc验证得16进制验证码字符串
		CRC16M crc1 = new CRC16M();
		//16进制字符串转字节数组用于得到其crc验证码
		String hexString1 = crc1.getCRCString(crcString);
		String responseData = head + crcString + hexString1 + end;
		//帧头+内容+crc验证码+帧尾
		byte[] bts = new byte[responseData.length()];
		//16进制字符串转10进制字节数组
		bts = ByteTransformer.hexString2Bytes(responseData);
	    ByteBuf encoded = ctx.alloc().buffer(4 * bts.length);  
	    encoded.writeBytes(bts);
	    ctx.write(encoded);
	    ctx.flush();
	}

	public static void main(String[] args) {
		String[] bts = ByteTransformer.to16Strbytes("ABC123".getBytes());
		for (int i = 0; i < bts.length; i++) {
			System.out.print(bts[i]);
		}
	}
	
}
